<template>
  <div class="settlement">
    <!-- 顶部 -->
    <van-nav-bar title="订单结算" left-arrow fixed @click-left="onClickLeft">
    </van-nav-bar>

    <div class="order-content">
      <!-- 店铺相关信息、客户电话 -->
      <div class="address-phone d-flex justify-content-between">
        <!-- 弹性左边 -->
        <div class="address-info">
          <keep-alive>
            <!-- 收藏按钮 -->
            <van-icon
              @click="collect"
              v-if="isCollect"
              name="star"
              color="#ff8c00"
              style="position: relative; top: 2px; margin-right: 5px"
            />
            <van-icon
              @click="collect"
              v-else
              name="star-o"
              style="position: relative; top: 2px; margin-right: 5px"
            />
          </keep-alive>

          <!-- 定位跳转 -->
          <router-link to="/store" style="color: black">
            <p
              style="
                display: inline-block;
                margin: 0;
                font-size: 15px;
                color: black;
              "
            >
              {{ addressTitle }}
            </p>
            <van-icon style="position: relative; top: 3px" name="arrow" />
          </router-link>
          <h6>
            <van-icon style="position: relative; top: 2px" name="location-o" />
            <span style="font-size: 14px; color: #666">请确认门店后下单</span>
          </h6>
          <span style="font-size: 15px">联系电话 {{ userPhone }}</span>
        </div>
        <!-- 弹性右边 -->
        <div>
          <button
            @click="changeBtn"
            class=""
            style="font-size: 12px; padding: 4px 5px; border: 0"
          >
            <span
              style="margin-right: 5px"
              :class="{ 'switch-btn': switchBtn == true }"
              >自取</span
            >
            <span :class="{ 'switch-btn': switchBtn == false }">外卖</span>
          </button>
          <div
            style="
              border: 1px solid #ff976a;
              color: #ff976a;
              text-align: center;
              font-size: 12px;
              margin-top: 22px;
            "
          >
            自动填写
          </div>
        </div>
      </div>

      <!-- 取餐时间 -->
      <div class="view-time">
        <h6>取餐时间</h6>
        <h2>
          <van-count-down millisecond :time="time" format="HH:mm:ss:SS" />
        </h2>
      </div>

      <!-- 购物车商品 -->
      <div class="cart-info">
        <h6>商品详情</h6>
        <p style="font-size: 12px">选购粥品，记得趁热吃哦</p>

        <!-- 已购买商品列表 -->
        <ul class="clearfix">
          <li
            class="store-info d-flex justify-content-between"
            v-for="(food, index) of cartFoods"
            :key="index"
          >
            <img :src="food.coverImg" alt="" />
            <div class="detail-name">
              <h6>{{ food.shopName }}</h6>
              <p>
                {{ food.shopIntroduction | shopIntrFilter }}
              </p>
            </div>
            <div class="">
              <h6>￥{{ food.originalPrice }}</h6>
              <!-- <p style="font-size: 12px">x{{ food.count }}</p> -->
              <div class="cartcontrol_wrapper">
                <CartControl :food="food" />
              </div>
            </div>
          </li>
        </ul>

        <van-cell title="粥品劵" to="/coupon" is-link value="暂无可用" />
        <van-cell title="备注" is-link value="口味、包装等要求" />
        <div style="float: right; margin-right: 15px">
          <span>共{{ totalCount }}件商品，小计 ￥{{ totalPrice }}</span>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="pay-way">
        <!-- @cancel="onCancel" -->
        <van-cell
          v-model="title"
          is-link
          title="支付方式"
          @click="show = true"
        />
        <!-- 隐藏框 -->
        <van-action-sheet
          style="margin-bottom: 66px"
          v-model="show"
          :actions="actions"
          cancel-text="取消"
          close-on-click-action
          @select="onSelect"
          title="支付方式"
        />
      </div>

      <!-- 留白 -->
      <div style="width: 100%; height: 100px"></div>
    </div>

    <!-- 底部支付 -->
    <div class="pay d-flex justify-content-end">
      <div class="money">合计：￥{{ totalPrice }}</div>
      <van-button class="pay-btn" round type="warning" @click="pay"
        >支付</van-button
      >
    </div>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
import { mapState, mapGetters } from "vuex";
import CartControl from "../components/CartControl/CartControl.vue";

export default {
  components: { CartControl },
  data() {
    return {
      time: 10 * 60 * 60 * 1000,
      show: false,
      title: "微信支付",
      actions: [{ name: "微信支付" }, { name: "支付宝" }],
      getInfo: {}, //地址定位
      userPhone: "", //用户手机号
      switchBtn: true, //按钮切换
      isCollect: false, //是否收藏
      collectStore: [], //用户收藏店铺
    };
  },
  // 定义过滤器
  filters: {
    shopIntrFilter(oldVal) {
      if (oldVal.length > 22) {
        return oldVal.slice(0, 30) + "...";
      }
    },
  },
  methods: {
    // 是否收藏
    collect() {
      // 是否清除定时器
      if (this.timer != null) {
        clearTimeout(this.timer);
      }
      this.isCollect = !this.isCollect;
      // 防抖
      this.timer = setTimeout(() => {
        //点击collect时，
        if (this.isCollect == true) {
          Toast("收藏成功");
        } else {
          Toast("取消收藏成功");
        }

        // 请求是否收藏
        this.axios
          .post(
            "/api/store/addFavoritesStore",
            `uid=${this.getInfo.uid}&address=${this.getInfo.address}&city=${this.getInfo.city}&province=${this.getInfo.province}&title=${this.getInfo.title}`
          )
          .then((result) => {
            // console.log(result);
          });
      }, 2000);
    },

    // 获得当前用户收藏列表
    getCollectStore() {
      this.axios.get("/api/store/getFavoritesStore").then((result) => {
        console.log(result.data.data);
        // this.collectStore = result.data.data;
        for (let item of result.data.data) {
          if (item.uid == this.getInfo.uid) {
            this.isCollect = true;
            console.log(item.uid);
          } else {
            this.isCollect = false;
          }
        }
        console.log(this.getInfo.uid);
      });
    },

    // 切换按钮
    changeBtn() {
      this.switchBtn = !this.switchBtn;
    },
    // 返回上一级
    onClickLeft() {
      this.$router.back(-1);
    },
    // 支付方式
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.show = false;
      if (item.name == "微信支付") {
        this.title = "微信支付";
        // console.log(this.title);
      } else {
        this.title = "支付宝";
        // console.log(this.title);
      }
    },
    // 支付跳转
    pay() {
      if (this.addressTitle == "暂时无法获取定位") {
        Dialog.alert({
          title: "提示",
          message: "请先选择当前地址",
        }).then(() => {
          // on close
        });
      } else {
        Dialog.confirm({
          title: "请确认自取门店",
          confirmButtonText: "我已确认",
          confirmButtonColor: "#ff8c00",
          cancelButtonText: "我想静静",
          message: `<span style="text-align:left;width:100%;display: inline-block;">${this.addressTitle}</span>
        <p style="text-align:left;margin:0">${this.addressDetail}</p>`,
        })
          .then(() => {
            // on close
            this.axios
              .post(
                "/api/order/submitOrder",
                `storeName=${this.addressTitle}&StoreUID=${this.getInfo.uid}`
              )
              .then(
                Toast.success("支付成功"),
                this.$store.dispatch("clearCart"),
                this.$router.push("/order")
              );
          })
          .catch((err) => {
            // on cancel
            console.log(err);
          });
      }
    },
    // 得到用户手机号
    getUserPhone() {
      // 获取当前用户id信息
      if (this.isLogin) {
        // 获得当前用户id
        this.axios
          .get(`/api/user/getUser?userId=${this.userId}`)
          .then((result) => {
            // console.log(result);
            // 用户信息
            this.userPhone = result.data.data.phone;
            // 测试当前用户信息
            // console.log(this.userPhone);
          });
      }
    },
  },
  // 结构变量
  computed: {
    ...mapState([
      "addressDetail",
      "addressTitle",
      "addressInfoNow",
      "userId",
      "isLogin",
      "cartFoods",
    ]), //是否定位
    ...mapGetters(["totalCount", "totalPrice"]),
    // 计算个数
    // sumshopCount() {
    //   let sum = 0;
    //   for (let item of this.cartFoods) {
    //     sum += item.count;
    //   }
    //   return sum;
    // },
    // totalPrice() {
    //   let totals = 0;
    //   for (let item of this.cartFoods) {
    //     totals += item.count * item.originalPrice;
    //   }
    //   return totals;
    // },
  },
  // beforeRouteUpdate(to, from, next) {
  //   console.log(this.cartFoods);
  //   console.info("获取Settlement页面数据");
  //   next();
  // },
  created() {},
  mounted() {
    // 测试获取当前店铺信息
    this.getInfo = this.addressInfoNow;
    // console.log(this.getInfo);
    if (typeof this.addressInfoNow == "string") {
      this.getInfo = JSON.parse(this.addressInfoNow);
    }
    // 得到用户手机号
    this.getUserPhone();
    // 获得收藏地址列表
    this.getCollectStore();

    // 得到uid
    // console.log(this.getInfo.uid);

    // 获取购物车列表信息 vuex
    // this.cartFoods = this.selectedFood;
    // console.log(this.selectedFood);

    // 获取购物车列表信息 数据库
    // this.axios
    //   .get(`/api/shop/getShopCart?userId=${this.userId}`)
    //   .then((result) => {
    //     //测试
    //     // console.log(result);
    //     this.cartFoods = result.data.data;
    //     //测试赋值
    //     console.log(this.cartFoods);
    //     // console.log(this.selectedFood);
    //   });
  },
};
</script>

<style lang="scss" scoped>
.order-content {
  position: fixed;
  bottom: 66px;
  top: 46px;
  left: 0;
  right: 0;
  overflow-y: scroll;
  .address-phone {
    // height: 100px;
    padding: 15px 5px;
    box-shadow: 0 0 5px #ccc;
  }
  .view-time {
    height: 100px;
    background-color: burlywood;
    margin: 10px auto;
  }
}

// 按钮切换
.switch-btn {
  color: white;
  background-color: black;
  padding: 5px 5px;
}

// 已购买的商品详情
.cart-info {
  ul {
    padding: 0;
    .store-info {
      margin: 0 15px;
      padding: 15px 0;
      border-bottom: 1px solid #ccc;
      position: relative;
      img {
        width: 20%;
        height: 20%;
      }
      .detail-name {
        width: 200px;
        p {
          font-size: 12px;
          margin: 0;
          color: rgb(147, 153, 159);
        }
      }
    }
  }
}
.cartcontrol_wrapper {
  position: absolute;
  right: 3px;
  bottom: 15px;
}

// 底部按钮支付
.pay {
  position: fixed;
  width: 100%;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  padding: 15px;
  box-shadow: 0 0 5px #ccc;
  background-color: white;
  .money {
    line-height: 36px;
    margin-right: 10px;
  }
  .pay-btn {
    display: inline-block;
    width: 88px;
    height: 36px;
  }
}
</style>